import axios from "axios";
import { message } from "ant-design-vue";

/**
 * 初始化axios实例
 */
const request = axios.create({
  baseURL: "http://localhost:8900/api/",
  timeout: 60000,
  headers: { "X-Custom-Header": "foobar" },
  withCredentials: true,
});

// 全局请求拦截器
request.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 全局响应拦截器
request.interceptors.response.use(
  function (response) {
    console.log(response);
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    const { data } = response;

    // 未登录
    if (data.code === 40100) {
      // 不是获取用户信息的请求，并且用户目前不是已经在用户登录页面，则跳转到登录页面
      if (
        !response.request.responseURL.includes("user/get/login") &&
        !window.location.pathname.includes("/user/login")
      ) {
        message.warn("请先登录");
        window.location.href = `/user/login?redirect=${window.location.href}`;
      }
    }

    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);
/**
 * 设置token
 */
export const setToken = (token: string) => {
  request.defaults.headers.common["token"] = token;
};

/**
 * 封装get方法
 */
export function get(url: string, params = {}) {
  return new Promise((resolve, reject) => {
    request
      .get(url, {
        params: params,
      })
      .then((response) => {
        resolve(response.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * 封装post方法
 */
export const post = (url: string, data = {}) => {
  return new Promise((resolve, reject) => {
    request
      .post(url, data)
      .then((response) => {
        resolve(response.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * 封装get方法(文件下载)
 */
export function getDownload(url: string, params = {}) {
  return new Promise((resolve, reject) => {
    request
      .get(url, {
        params: params,
        responseType: "blob",
      })
      .then((response) => {
        resolve(response.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export default request;
